<template>
  <view>
    <view class="modal" v-if="allNum[dir] > 0">
      <transition-group class="msgWrap" :class="['msg_' + dir]" tag="ul" name="msg">
        <li v-for="item, index in msgList" :key="item.id" :style="item.width ? 'width:' + `${item.width}rpx` : ''"
          class="msg">
          <text>{{ item.text }}</text>
        </li>
      </transition-group>
    </view>
  </view>
</template>
<script setup lang="ts">
/**
 * 
 @param {
    width number  容器宽度
    position  string 弹出方向
    time  number   弹出时间
    text  string  弹出文字 
 }
 */
import { ref, nextTick, toRefs, reactive, watch } from 'vue';
import { random_ } from '@/hooks'
const { randomString, randomValue } = random_()
export interface Props {
  width?: number | string,
  position?: string,
  time?: number | string,
  text?: string,
}
const props = withDefaults(defineProps<Props>(), {
  width: 0,
  position: 'center',
  time: 1500,
  text: '',
})
const msgList = ref<any>([])
const allNum = reactive({
  top: 0,
  left: 0,
  bottom: 0,
  right: 0,
  center: 0
})
const dir = ref<string>('')
const random = ref<string>('')
const { position, text, width, time } = toRefs(props)
function show(opts: any) {
  const pos_ = opts.position || position.value
  randomString(12)
  random.value = randomValue
  dir.value = pos_
  allNum[pos_]++
  if (!allNum[pos_]) {
    allNum[pos_] = 0
  }
  if (pos_ === "top") {
    msgList.value.push({
      text: opts.text || text.value,
      width: opts.width || width.value,
      id: random.value
    })
  } else {
    msgList.value.unshift({
      text: opts.text || text.value,
      width: opts.width || width.value,
      id: random.value
    })
  }
  setTimeout(() => {
    delMsg(pos_, random.value)
  }, opts.time || time.value)
}
function delMsg(dir, id) {
  for (let i = msgList.value.length; i--;) {
    allNum[dir]--
    if (msgList.value[i].id === id.value) {
      msgList.value.splice(i, 1)
      break
    }
  }
}
defineExpose({
  show
})

</script>
<style scoped lang="scss">
@import "./index.scss";
</style>